package com.mark.imagedemo.controller;

import com.mark.imagedemo.utils.FileUploadUtil;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 图片上传对的Controller
 *
 * @author Markcc
 * @date 2018/11/29-8:57
 * @email markerccc@163.com
 */
@RestController
@RequestMapping("/")
public class ImageUploadController {

    /**
     * @param imageFile
     * @param request
     * @return
     */
    @PostMapping("/uploadImage")
    public Map<String, String> uploadImage(@RequestParam("imageFile") MultipartFile imageFile, HttpServletRequest request) {
        HashMap<String, String> filePathMap = new HashMap<>();
        //得到文件上传的类型
        String contentType = imageFile.getContentType();

        /**
         * 得到图片名称
         */
        String fileName = FileUploadUtil.getFileName(imageFile.getOriginalFilename());
        String maxFileName = "max" + fileName;
        String minFileName = "min" + fileName;
        String filePath = "D://a//";
        try {
            FileUploadUtil.FileUpload(imageFile.getBytes(), fileName, filePath);
            // 对图片进行裁剪   http://rensanning.iteye.com/blog/1545708
            Thumbnails.of(filePath + fileName).sourceRegion(Positions.CENTER, 400, 400).size(400, 400).toFile(filePath + maxFileName);
            Thumbnails.of(filePath + fileName).sourceRegion(Positions.CENTER, 400, 400).size(200, 200).toFile(filePath + minFileName);
        } catch (IOException e) {
            e.printStackTrace();
        }

        filePathMap.put("filePath", filePath + fileName);
        filePathMap.put("maxPath", filePath + maxFileName);
        filePathMap.put("minPath", filePath + minFileName);
        return filePathMap;
    }
}
